package com.hualude.roadsign.repository;

import com.hualude.roadsign.dto.HighLeverDto;
import com.hualude.roadsign.dto.HighLeverFaultDto;
import com.hualude.roadsign.dto.DTRequestDto;
import com.hualude.roadsign.dto.FaultCountDto;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

import static com.hualude.roadsign.service.impl.CountServiceImpl.convertParams;

/**
 * Created by xu_jiaHui on 2018/3/24.
 */
public class HighLeverFaultCountRepositoryImpl {

    @PersistenceContext
    private EntityManager em;

    public List<String> getDealCounts(Integer year, String orgIds) throws Exception {
        Integer yearNext = year + 1;
        String hql = "select m.HighLeverMaintenanceTime from tb_highLever_fault m,tb_user u where m.HighLeverMaintenanceStatus = 2 and " +
                "(m.HighLeverMaintenanceTime between '" + year + "' and '" + yearNext + "') and m.HighLeverMaintainerId = u.userId and u.orgId in (" + orgIds + ")";
        Query query = em.createNativeQuery(hql);
        List<String> times = query.getResultList();
        return times;
    }

    public List<String> getReportCounts(Integer year, String orgIds) throws Exception {
        Integer yearNext = year + 1;
        String hql = "select s.HighLeverFaultTime from tb_highLever_fault s where " +
                "(s.HighLeverFaultTime between '" + year + "' and '" + yearNext + "') and  (s.HighLeverOrgId in (" + orgIds + ") or " +
                "s.HighLeverMainOrgId in (" + orgIds + "))";
        Query query = em.createNativeQuery(hql);
        List<String> times = query.getResultList();
        return times;
    }

    public List<FaultCountDto> getExpenseCounts(Integer year, String orgIds) throws Exception {
        Integer yearNext = year + 1;
        String hql = "select m.HighLeverMaintenanceTime AS maintenanceTime,m.HighLeverMoney AS repairAmount from tb_highLever_fault m,tb_user u where " +
                "(m.HighLeverMaintenanceTime between '" + year + "' and '" + yearNext + "') and m.HighLeverMaintainerId = u.userId and u.orgId in (" + orgIds + ")";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(FaultCountDto.class));
        List<FaultCountDto> maintenanceDtos = query.getResultList();
        return maintenanceDtos;
    }

    public List<HighLeverFaultDto> getFault4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select f.HighLeverFaultId,f.HighLeverId,f.HighLeverFaultPhoto,p.HighLeverPhoto,f.HighLeverFaultLevel,f.HighLeverCheck,f.HighLeverMainCheck,\n" +
                "f.HighLeverFaultTime,f.HighLeverCheckTime,o.OrgName AS highLeverOrgName,o2.orgName as highLeverMainOrgName,p.HighLeverPeriod," +
                " p.HighLeverStartRoad,p.HighLeverEndRoad,p.HighLeverRoadName,p.HighLeverServiceLife,p.HighLeverSize,\n" +
                "p.HighLeverArea,p.HighLeverCity,p.HighLeverProvince,u.UserName AS highLeverFaultCreatorName\n" +
                "from tb_highLever_fault f,tb_org o,tb_org o2,tb_highLever p,tb_user u\n" +
                "where f.HighLeverOrgId = o.OrgId and p.HighLeverMainOrgId=o2.orgId and f.HighLeverId = p.HighLeverId  AND\n" +
                "f.HighLeverFaultCreatorId = u.UserId";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and f.HighLeverFaultTime between '" + dateStr[0] + "' and '" + dateStr[1] + 1 + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (f.HighLeverOrgId IN (" + orgIds + ") or " +
                    "f.HighLeverMainOrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY f.HighLeverFaultTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(HighLeverFaultDto.class));
        List<HighLeverFaultDto> roadpoleDto = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return roadpoleDto;
    }

    public Integer getFaultCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select count(*) from tb_highLever_fault f,tb_org o WHERE f.HighLeverOrgId= o.OrgId";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and f.HighLeverFaultTime between '" + dateStr[0] + "' and '" + dateStr[1] + 1 + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (f.HighLeverOrgId IN (" + orgIds + ") or " +
                    "f.HighLeverMainOrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public List<HighLeverFaultDto> getDevice4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds, Integer userId) throws Exception {
        String hql = "select m.HighLeverFaultId,m.HighLeverFaultPhoto,m.HighLeverMaintenancePhoto,m.HighLeverMaintenanceStatus,m.HighLeverMaintenanceTime,HighLeverMoney,\n" +
                "o.OrgName AS highLeverOrgName,m.HighLeverId,s.HighLeverEndRoad,s.HighLeverStartRoad,s.HighLeverArea,s.HighLeverRoadName,s.HighLeverServiceLife,s.HighLeverSize,\n" +
                "s.HighLeverCity,s.HighLeverProvince,o2.orgName as highLeverMainOrgName,s.HighLeverPhoto,s.HighLeverPeriod,u.UserName AS highLeverFaultCreatorName\n" +
                "from tb_highLever_fault m,tb_user u,tb_org o,tb_org o2,tb_highLever s \n" +
                "where m.HighLeverMaintenanceStatus=2 and m.HighLeverMaintainerId = u.userId and s.HighLeverMainOrgId=o2.orgId\n" +
                "and u.OrgId = o.OrgId and m.HighLeverId = s.HighLeverId ";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and m.HighLeverMaintenanceTime between '" + dateStr[0] + "' and '" + dateStr[1] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (u.OrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY m.HighLeverMaintenanceTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(HighLeverFaultDto.class));
        List<HighLeverFaultDto> roadpoleDto = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return roadpoleDto;
    }

    public Integer getDeviceCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds, Integer userId) throws Exception {
        String hql = "select count(*) from tb_highLever_fault m,tb_user u,tb_org o,tb_org o2,tb_highLever s \n" +
                "where m.HighLeverMaintenanceStatus=2 and m.HighLeverMaintainerId = u.userId and s.HighLeverMainOrgId=o2.orgId\n" +
                "and u.OrgId = o.OrgId and m.HighLeverId = s.HighLeverId ";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and m.HighLeverMaintenanceTime between '" + dateStr[0] + "' and '" + dateStr[1] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (u.OrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public Integer getHighLeverCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select count(*) from tb_highLever where HighLeverId like '%'";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        //0:省 1:市 2:区域 3:道路 4:起始路段 5:终止路段 6:主管单位 7:养护公司
        if (!sQuery[0].equals("-1")) {
            hql += " and HighLeverProvince = '" + sQuery[0] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and HighLeverCity = '" + sQuery[1] + "'";
        }
        if (!sQuery[2].equals("-1")) {
            hql += " and HighLeverArea = '" + sQuery[2] + "'";
        }
        if (!sQuery[3].equals("-1")) {
            hql += " and HighLeverRoadName ='" + sQuery[3] + "'";
        }
        if (!sQuery[4].equals("-1") && sQuery[5].equals("-1")) {
            hql += " and (HighLeverStartRoad ='" + sQuery[4] + "' or HighLeverEndRoad ='" + sQuery[4] + "')";
        }
        if (sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and (HighLeverEndRoad ='" + sQuery[5] + "' or HighLeverStartRoad ='" + sQuery[5] + "')";
        }
        if (!sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and ((HighLeverStartRoad ='" + sQuery[4] + "' and HighLeverEndRoad ='" + sQuery[5] + "') or" +
                    "(HighLeverStartRoad = '" + sQuery[5] + "' and HighLeverEndRoad = '" + sQuery[4] + "'))";
        }
        if (!sQuery[6].equals("-1")) {
            hql += " and HighLeverMainOrgId = '" + sQuery[6] + "'";
        }
        if (!sQuery[7].equals("-1")) {
            hql += " and HighLeverOrgId = '" + sQuery[7] + "'";
        }
        if (actor != 1) {
            hql += " and (HighLeverOrgId IN (" + orgIds + ") or " +
                    "HighLeverMainOrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public List<HighLeverDto> getHighLever4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select c.HighLeverId,c.HighLeverPhoto,c.HighLeverProvince,c.HighLeverCity,c.HighLeverArea," +
                "c.HighLeverRoadName,e.OrgName as highLeverMainOrgName,o.OrgName as highLeverOrgName," +
                "c.HighLeverSize,c.HighLeverInstallTime,c.HighLeverStartRoad," +
                "c.HighLeverEndRoad,c.HighLeverIsComplete from tb_highLever c " +
                "LEFT JOIN tb_org e ON c.HighLeverMainOrgId = e.OrgId " +
                "LEFT JOIN tb_org o ON c.HighLeverOrgId = o.OrgId " +
                "where c.HighLeverId LIKE '%'";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        //0:省 1:市 2:区域 3:道路 4:起始路段 5:终止路段 6:主管单位 7:养护公司
        if (!sQuery[0].equals("-1")) {
            hql += " and HighLeverProvince = '" + sQuery[0] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and HighLeverCity = '" + sQuery[1] + "'";
        }
        if (!sQuery[2].equals("-1")) {
            hql += " and HighLeverArea = '" + sQuery[2] + "'";
        }
        if (!sQuery[3].equals("-1")) {
            hql += " and HighLeverRoadName ='" + sQuery[3] + "'";
        }
        if (!sQuery[4].equals("-1") && sQuery[5].equals("-1")) {
            hql += " and (HighLeverStartRoad ='" + sQuery[4] + "' or HighLeverEndRoad ='" + sQuery[4] + "')";
        }
        if (sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and (HighLeverEndRoad ='" + sQuery[5] + "' or HighLeverStartRoad ='" + sQuery[5] + "')";
        }
        if (!sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and ((HighLeverStartRoad ='" + sQuery[4] + "' and HighLeverEndRoad ='" + sQuery[5] + "') or" +
                    "(HighLeverStartRoad = '" + sQuery[5] + "' and HighLeverEndRoad = '" + sQuery[4] + "'))";
        }
        if (!sQuery[6].equals("-1")) {
            hql += " and HighLeverMainOrgId = '" + sQuery[6] + "'";
        }
        if (!sQuery[7].equals("-1")) {
            hql += " and HighLeverOrgId = '" + sQuery[7] + "'";
        }
        if (actor != 1) {
            hql += " and (HighLeverOrgId IN (" + orgIds + ") or " +
                    "HighLeverMainOrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY c.HighLeverInstallTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(HighLeverDto.class));
        List<HighLeverDto> monitorDtos = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return monitorDtos;
    }

    public List<String> getProvinceName(String orgIds) throws Exception {
        String hql = "select distinct c.HighLeverProvince from tb_highLever c where c.HighLeverOrgId in (" + orgIds + ") or " +
                "c.HighLeverMainOrgId in (" + orgIds + ")";
        hql += " order by convert(c.HighLeverProvince using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> province = query.getResultList();
        return province;
    }

    public List<String> getCityName(String orgIds, String provinceName) throws Exception {
        String hql = "select distinct c.HighLeverCity from tb_highLever c where (c.HighLeverOrgId in (" + orgIds + ") or " +
                "c.HighLeverMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.HighLeverProvince = '" + provinceName + "'";
        }
        hql += " order by convert(c.HighLeverCity using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> city = query.getResultList();
        return city;
    }

    public List<String> getAllAreaName(String orgIds, String provinceName, String cityName) throws Exception {
        String hql = "select distinct c.HighLeverArea from tb_highLever c where (c.HighLeverOrgId IN (" + orgIds + ")" +
                " or c.HighLeverMainOrgId IN (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.HighLeverProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.HighLeverCity ='" + cityName + "'";
        }
        hql += " order by convert(c.HighLeverArea using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> area = query.getResultList();
        return area;
    }

    public List<String> getRoadNames(String provinceName, String cityName, String areaName, String orgId, Integer actor) throws Exception {
        String hql = "select distinct c.HighLeverRoadName from tb_highLever c where (c.HighLeverOrgId in (" + orgId + ") or " +
                "c.HighLeverMainOrgId in (" + orgId + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.HighLeverProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.HighLeverCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and c.HighLeverArea = '" + areaName + "'";
        }
        hql += " order by convert(c.HighLeverRoadName using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<String> getStartRoadName(String orgIds, String provinceName, String cityName, String areaName,
                                         String endRoadName, String roadName) throws Exception {
        String hql = "select distinct c.HighLeverStartRoad from tb_highLever c where (c.HighLeverOrgId in (" + orgIds + ") or " +
                "c.HighLeverMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.HighLeverProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.HighLeverCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and c.HighLeverArea = '" + areaName + "'";
        }
        if (!endRoadName.equals("-1")) {
            hql += " and c.HighLeverEndRoad = '" + endRoadName + "'";
        }
        if (!roadName.equals("-1")) {
            hql += " and c.HighLeverRoadName = '" + roadName + "'";
        }
        hql += " order by convert(c.HighLeverStartRoad using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<String> getEndRoadName(String orgIds, String startRoad, String provinceName, String cityName,
                                       String areaName, String roadName) throws Exception {
        String hql = "select distinct c.HighLeverEndRoad from tb_highLever c where (c.HighLeverOrgId in (" + orgIds + ") or " +
                "c.HighLeverMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.HighLeverProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.HighLeverCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and c.HighLeverArea = '" + areaName + "'";
        }
        if (!startRoad.equals("-1")) {
            hql += " and c.HighLeverStartRoad = '" + startRoad + "'";
        }
        if (!roadName.equals("-1")) {
            hql += " and c.HighLeverRoadName = '" + roadName + "'";
        }
        hql += " order by convert(c.HighLeverEndRoad using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<Integer> getHighLeverTypeCounts(String orgIds, String time, String province, String city, String area, String road) throws Exception {
        String[] timeLimit = {"", ""};
        timeLimit = time.split(" - ");
        String hql = "select COUNT(*) from tb_highLever c  where (c.HighLeverOrgId in (" + orgIds + ") or " +
                "c.HighLeverMainOrgId in (" + orgIds + ")) AND (c.HighLeverInstallTime between '" + timeLimit[0] + "' and '" + timeLimit[1] + "') " +
                " and c.HighLeverProvince like '%" + province + "%' and c.HighLeverCity like '%" + city + "%' " +
                " and c.HighLeverArea like '%" + area + "%' and c.HighLeverRoadName like '%" + road + "%' ";
        Query query = em.createNativeQuery(hql);
        List<Integer> counts = query.getResultList();
        return counts;
    }
}
